package com.zy.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.entity.JsonResult;
import com.zy.entity.User;
import com.zy.mapper.UserMapper;
import com.zy.service.impl.UserServiceImpl;
import com.zy.tools.RedisTool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("/app")
public class LoginController {
    @Autowired
    UserServiceImpl userService;
    @Autowired
    RedisTool redisTool;
    JSONObject json = new JSONObject();
    @Autowired
    private UserMapper userMapper;

    /* 小程序-用微信Code登录
     * @author 小宁
     * @date 2021-04-03 15:59
     * @param wxcode
     * @return com.zy.entity.JsonResult
     */
    @GetMapping("/login")
    @ResponseBody
    public JsonResult login(String wxcode) throws IOException {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx4c06dc20718f16d7&secret=" +
                "908185613dc6a98df3d50385c525f4a6&js_code=" + wxcode + "&grant_type=authorization_code";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = okHttpClient.newCall(request).execute();

        if (response.isSuccessful()) {
            String body = response.body().string();
            json = JSONObject.parseObject(body);
            String openid = json.getString("openid");
            System.out.println("openid " + openid);
            json.clear();

            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("open_id", openid);
            System.out.println("openid  " + openid);

            User user = userService.getOne(userQueryWrapper);
            user.setOpenId(null);
            Map<String, String> departmentMap = userMapper.getDepartmentName(user.getId());

            json.put("user", user);
            json.put("departmentMap", departmentMap);//返回用户所在部门

            if (user == null) {
                return new JsonResult("201", "用户不存在", "");
            } else {
                return new JsonResult("200", "登录成功", json);
            }
        } else {
            return new JsonResult("500", "网络错误，重试", "");
        }

    }

    /**
     * 每日好文
     *
     * @return com.zy.entity.JsonResult
     * @author 小宁
     * @date 2021-04-16 11:09
     */
    @ResponseBody
    @GetMapping("/getYiWen")
    public JsonResult getYiWen() throws IOException {
        SimpleDateFormat sf = new SimpleDateFormat("YYYYMMdd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.YEAR, -1);
        Date start = c.getTime();
        String startDay = sf.format(start);//前一年
        String body = null;

        if (redisTool.hasKey(startDay)) {
            json = (JSONObject) redisTool.get(startDay);
        } else {
            String url = "https://interface.meiriyiwen.com/article/day?dev=1&date=" + startDay;
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder().url(url).header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0").build();
            Response response = okHttpClient.newCall(request).execute();
            body = response.body().string();

            json = JSON.parseObject(body);
            redisTool.set(startDay, json, 60 * 60 * 24);
        }
        return new JsonResult("200", "", json);
    }


}
